package com.ddh.ddhsanguogame.webSocket.service;

import com.ddh.ddhsanguogame.constant.MessageTypeConstants;
import com.ddh.ddhsanguogame.constant.RedisConstant;
import com.ddh.ddhsanguogame.exception.DongException;
import com.ddh.ddhsanguogame.exception.ErrorCode;
import com.ddh.ddhsanguogame.utils.RedisService;
import com.ddh.ddhsanguogame.webSocket.entity.CardMessageRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class MessageService {


    private static final long DEFAULT_MAX_HISTORY_SIZE = 100;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private RedisService redisService;

    /**
     * 保存消息到Redis历史记录
     *
     * @param message 消息内容
     */
    @SneakyThrows
    public void saveMessage(String message) {
        CardMessageRequest cardMessageRequest = objectMapper.readValue(message, CardMessageRequest.class);
        String messageType = cardMessageRequest.getMessageType();
        redisService.setList(messageType, message);
    }

    /**
     * 保存私聊消息到Redis
     *
     * @param message 消息内容（JSON字符串）
     */
    @SneakyThrows
    public void savePrivateMessage(String message) {
        CardMessageRequest cardMessageRequest = objectMapper.readValue(message, CardMessageRequest.class);
        Long receiverId = cardMessageRequest.getReceiverId();
        Long senderId = cardMessageRequest.getSenderId();
        String messageType = cardMessageRequest.getMessageType();
        if (receiverId == null) {
            throw new DongException(ErrorCode.PRIVATE_MESSAGE_REQUIRES_RECEIVER_ID);
        }
        // 保存到全局私聊记录
        redisService.setList(messageType, message);
    }
}
